package com.tyfspring.beans.support;

import com.tyfspring.beans.FactoryBean;
import com.tyfspring.beans.exception.BeansException;
import com.tyfspring.beans.factory.DefaultSingletonBeanRegistry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 处理关于FactoryBean此类对象的注册
 * @Author shallow
 * @Date 2023/4/12 19:49
 */

public class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
    //定义了缓存操作，用于存放单例类型的对象，避免重复创建
    private final Map<String,Object> factoryBeanObjectCache =new ConcurrentHashMap<>();

    protected Object getCachedObjectForFactoryBean(String beanName){
        Object object = this.factoryBeanObjectCache.get(beanName);
        return (object != NULL_OBJECT?object:null);
    }

    protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName){
        if (factory.isSingleton()){
            Object object = this.factoryBeanObjectCache.get(beanName);
            if (null == object){
                object = doGetObjectFromFactoryBean(factory,beanName);
                this.factoryBeanObjectCache.put(beanName,(object!=null?object:NULL_OBJECT));
            }
            return (object!=NULL_OBJECT?object:null);
        }else{
            return doGetObjectFromFactoryBean(factory,beanName);
        }
    }

    private Object doGetObjectFromFactoryBean(FactoryBean factory, String beanName) {
        try {
            return factory.getObject();
        } catch (Exception e) {
            throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation", e);
        }
    }
}
